Page({
  data: {
    shopUrl: '',
    shopName: ''
  },

  onShareAppMessage() {
    return {};
  },

  // 返回上一页
  handleBack() {
    wx.navigateBack({
      delta: 1
    });
  },

  // 验证淘宝店铺链接
  validateShopUrl(url) {
    // 支持多种格式的淘宝店铺链接
    const patterns = [
      /^https?:\/\/shop(\d{1,12})\.taobao\.com\/?.*$/,  // 标准店铺链接
      /^https?:\/\/(\w+\.)?taobao\.com\/shop\/view_shop\.htm\?.*user_number_id=(\d{1,12}).*$/,  // 查看店铺链接
      /^https?:\/\/(\w+\.)?taobao\.com\/shop\/(\d{1,12}).*$/  // 简短店铺链接
    ];

    for (const regex of patterns) {
      const match = url.match(regex);
      if (match) {
        // 返回店铺ID，根据不同格式取不同的匹配组
        return match[1] || match[2];
      }
    }

    wx.showToast({
      title: '请输入正确的淘宝店铺链接',
      icon: 'none',
      duration: 2000
    });
    return null;
  },

  // 处理微信注册
  async handleWechatRegister() {
    try {
      // 验证输入
      if (!this.data.shopUrl || !this.data.shopName) {
        wx.showToast({
          title: '请填写完整信息',
          icon: 'none',
          duration: 2000
        });
        return;
      }

      // 验证店铺链接
      const shopId = this.validateShopUrl(this.data.shopUrl);
      if (!shopId) {
        return;
      }

      // 获取用户信息
      const userInfoRes = await wx.getUserProfile({
        desc: '用于完善商家资料'
      });

      // 调用注册云函数
      const registerRes = await wx.cloud.callFunction({
        name: 'register',
        data: {
          type: 'merchant',
          userInfo: userInfoRes.userInfo,
          extraData: {
            shopName: this.data.shopName,
            taobaoUrl: this.data.shopUrl,
            taobaoId: shopId
          }
        }
      });

      if (registerRes.result.error) {
        throw new Error(registerRes.result.error);
      }

      // 存储用户信息到本地
      wx.setStorageSync('userInfo', {
        ...userInfoRes.userInfo,
        userId: registerRes.result.userId,
        type: 'merchant',
        shopName: this.data.shopName,
        taobaoId: shopId
      });

      // 注册成功，跳转到商家主页
      wx.reLaunch({
        url: '/pages/merchant/home/index'
      });

    } catch (error) {
      console.error('注册失败:', error);
      wx.showToast({
        title: error.message || '注册失败，请重试',
        icon: 'none',
        duration: 2000
      });
    }
  }
});